/**
 * 
 */
package com.xbang.attendance.web.action.system.sign2;

import java.io.File;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.demo2do.lighturl.annotation.Action;
import com.xbang.attendance.entity.Sign.detail;
import com.xbang.attendance.service.AnalyzeService;
import com.xbang.attendance.service.ProductService;
import com.xbang.attendance.service.SystemService;
import com.xbang.core.struts.support.BaseActionSupport;
import com.xbang.core.utils.DateUtils;
import com.xbang.core.utils.FileUtils;

/**
 * @author dev.zhang
 * 
 */
/**
 * @author 李柯
 *
 */
public class Import extends BaseActionSupport {

	private static final long serialVersionUID = 4037486937918127712L;

	@Autowired
	private ProductService productService;

	private File file;

	private String fileFileName;

	@Autowired
	private SystemService systemService;
     
	@Action("/system/sign/import/do")
	public void doImport() throws Exception {
		Map parameters =  new HashMap<String, String>();
		Map datemap =new HashMap<String, String>();
		String sql = "delete from detail";
		systemService.execute(sql, null);
		sql = " SELECT * FROM userinfo";
	    List <Map> list=systemService.queryForList(sql, parameters);
	    if(list.size()>0&&list!=null){
	    	for(Map map : list){
	    	String useId =	map.get("userId").toString();
	    		//公司签到
	    	    //当前用户所以公司签到信息
	    		Insertrow(parameters, datemap, map, useId,"0");//公司签到
	    		Insertrow(parameters, datemap, map, useId,"1");//外勤签到
	    	    sql = "SELECT * FROM actioninfo WHERE actionType='3'";
	    		Insertrow(parameters,map,sql);                                               //请假 （只要是请假全过，没有请假规则）
	    	}
	    	
	    }

	}
	public String execute() throws Exception {
	
		 	return "";
	}
    
	private void Insertrowout( Map parameters,Map map,String sql,List<Map> listmap,String type) {
		// TODO Auto-generated method stub
		 // List <Map> Qj=systemService.queryForList(sql,parameters); 
	         for(Map detailclass : listmap){
	     	if(!detailclass.isEmpty()){
	     		detail detail = new detail();
	     		detail.setDepartment(null);
	     		String	endTime = detailclass.get("Max(signintime)").toString();
             	String endtimedate = endTime;
             	detail.setGpsEndtime(endTime);
		        	detail.setUserName(map.get("userName").toString());
		        	String date =detailclass.get("signintime").toString().substring(0, 10);
		        	detail.setDate(date);
		            detail.setType("");
		            if("0".equals(type)){
 		        		detail.setType("公司签到");
 		        	}else if ("1".equals(type)){
 		        		detail.setType("外勤签到");
 		        	}
		        //	String endTime = detailclass.get("gpsTime").toString();
		        	//detail.setGpsEndtime(endTime);
//		            long lateor =	getdate(startTime,date+" 09:30:00");
//		        	if(lateor>60*30){
//		            detail.setLateor("是");
//		        	}else{
//		        	detail.setLateor("否");	
//		        	}
		        	detail.setLateTime(detailclass.get("lateTime").toString());
		        	detail.setOutAddress(detailclass.get("address").toString());
		        	detail.setRecordOuttime(detailclass.get("signintime").toString());
		        	detail.setDistance(detailclass.get("distance").toString());//deviceId
		        	detail.setDeviceId(detailclass.get("deviceId").toString());		    		  
		        	detail.setDevicenum(detailclass.get("deviceType").toString());
		           try {
					systemService.save(detail);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
	     	}
	     	}
	}
	
	
	/**
	 * @param parameters
	 * @param map
	 * @param sql
	 */
	private void Insertrow( Map parameters,Map map,String sql) {
		// TODO Auto-generated method stub
        
         List <Map> Qj=systemService.queryForList(sql,parameters); 
         for(Map detailclass : Qj){
     	if(!detailclass.isEmpty()){
     		detail detail = new detail();
     		detail.setDepartment(null);
	        	detail.setUserName(map.get("userName").toString());
	        	String date =detailclass.get("signintime").toString().substring(0, 10);
	        	detail.setDate(date);
	            detail.setType("请假");
	        	String startTime = detailclass.get("gpsTime").toString();
	        	detail.setGpsStarttime(startTime);
//	            long lateor =	getdate(startTime,date+" 09:30:00");
//	        	if(lateor>60*30){
//	            detail.setLateor("是");
//	        	}else{
//	        	detail.setLateor("否");	
//	        	}
	        	detail.setLateTime(detailclass.get("lateTime").toString());
	        	detail.setOnAddress(detailclass.get("address").toString());
	        	detail.setRecordOntime(detailclass.get("signintime").toString());
	        	detail.setDistance(detailclass.get("distance").toString());//deviceId
	        	detail.setDeviceId(detailclass.get("deviceId").toString());		    		  
	        	detail.setDevicenum(detailclass.get("deviceType").toString());
	           try {
				systemService.save(detail);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
     	}
     	}
	}
	/**
	 * @param parameters
	 * @param datemap
	 * @param map
	 * @param useId
	 * @param actionType
	 * @throws Exception
	 */
	private void Insertrow(Map parameters, Map datemap, Map map, String useId,String actionType)
			throws Exception {
		String sql;
		sql = "SELECT signintime,userId,actionType ,actionSubType FROM  actioninfo WHERE actionType='"+actionType+"' AND actionSubType ='0' AND userId ='"+useId+"'";
		//，我来了的所有信息
		List <Map> company=systemService.queryForList(sql, parameters); 
		if(!company.isEmpty()){
			for(Map date : company){
		    	String date1 =date.get("signintime").toString().substring(0, 10); //签到日期  年-月-日
		    	if(!"".equals(date1)&&date1!=null){
		    		datemap.put(date1, date1);		    		
		    	}
			}
			
			if(datemap.size()>0&&datemap!=null){
				 Set set = datemap.entrySet();
			        for (Iterator<Map.Entry> it = set.iterator(); it.hasNext();) {
			            Map.Entry entry = (Map.Entry) it.next();
			        	String date =(String) entry.getValue();
			            System.out.println(entry.getKey() + "--->" + entry.getValue());
			            sql = "SELECT *,min(signintime) FROM  actioninfo WHERE actionType='"+actionType+"' AND actionSubType ='0' AND userId ='"+useId+"' AND signintime>('"+date+"'  - INTERVAL 1 SECOND) AND  signintime< INTERVAL 1 DAY + '"+date+"'";
			            List <Map> checkon=systemService.queryForList(sql, parameters);
			            if(!checkon.isEmpty()){
			            	
			            	 for(Map detailclass : checkon){ //签到明细对象的部分数据（我来了）
			            		 if(detailclass.get("min(signintime)")!=null){
			            				detail detail = new detail();
		 		    		        	detail.setDepartment(null);
		 		    		        	detail.setUserName(map.get("userName").toString());
		 		    		        	detail.setDate(date);
		 		    		        	if("0".equals(actionType)){
		 		    		        		detail.setType("公司签到");
		 		    		        	}else if ("1".equals(actionType)){
		 		    		        		detail.setType("外勤签到");
		 		    		        	}
		 		    		        	
		 		    		        	String startTime = detailclass.get("min(signintime)").toString();
		 		    		        	detail.setGpsStarttime(startTime);
		 		    		            long lateor =	getdate(startTime,date+" 09:30:00");
		 		    		        	if(lateor>60*30){
		 		    		            detail.setLateor("是");
		 		    		        	}else{
		 		    		        	detail.setLateor("否");	
		 		    		        	}
		 		    		        	detail.setOnAddress(detailclass.get("address").toString());
		 		    		        	detail.setRecordOntime(detailclass.get("signintime").toString());
		 		    		        	detail.setDistance(detailclass.get("distance").toString());//deviceId
		 		    		        	detail.setDeviceId(detailclass.get("deviceId").toString());		    		  
		 		    		        	detail.setDevicenum(detailclass.get("deviceType").toString());
		 		    		        	//我走了
		 
		 		    		        	sql="SELECT *,Max(signintime) FROM  actioninfo WHERE actionType='"+actionType+"' AND actionSubType ='1' AND userId ='"+useId+"' AND signintime>('"+date+"'  - INTERVAL 1 SECOND) AND  signintime< INTERVAL 1 DAY + '"+date+"'";	  
		 		    		        	List <Map> checkout=systemService.queryForList(sql, parameters);
		 	    		                if(checkout.size()>0&&checkout!=null&&!checkout.isEmpty()){
		 	    		                	Map mapchekout = checkout.get(0);
		 	    		                	if(mapchekout.get("Max(signintime)")!=null){
		 	    		                		String	endTime = mapchekout.get("Max(signintime)").toString();
			 	    		                	String endtimedate = endTime;
			 	    		                	detail.setGpsEndtime(endTime);
			 	    		                	// String workHour =  时间差  
			 	    		                 		            
			 	    		                	detail.setOutAddress(mapchekout.get("address").toString());
			 	    		                	detail.setRecordOuttime(mapchekout.get("signintime").toString());
			 	    		                	//晚到
			 	    		                	sql="SELECT *,Max(signintime) FROM  actioninfo WHERE actionType='"+actionType+"' AND actionSubType ='2' AND userId ='"+useId+"' AND signintime>('"+date+"'  - INTERVAL 1 SECOND) AND  signintime< INTERVAL 1 DAY + '"+date+"'";
			 	    		                	List <Map> late=systemService.queryForList(sql, parameters);
			 	    		                	if(late.size()>0&&late!=null&&!late.isEmpty()){
			 	    		                		Map latemap = late.get(0);
			 	    		                		if(!latemap.isEmpty()&& latemap.get("id")!=null&&latemap.get("Max(signintime)")!=null){detail.setLateTime(latemap.get("lateTime").toString());  }
			 	    		                		  		                		
			 	    		                	}else{
			 	    		                		System.out.print("没有迟到信息");
			 	    		                	}
			 	    		                long hour =   getdate(endTime,startTime);
			 	    		                if(hour>=0){
			 	    		                	String hourStr =String.valueOf(hour);
			 	    		                	  detail.setWorkHour(hourStr);	
					 	    		              systemService.save(detail); 
			 	    		                }
		                                    		                	
			 	    		                //	outAddress
			 	    		                	//recordOuttime    		                	
			 	    		                  }    else{  
			 	    		                	  // 外勤或公司签到
			 	    		                		if("0".equals(actionType)){
			 	    		                			  System.out.println("本次没有公司签出记录，可能在外勤");
					 	    		                	  sql="SELECT *,Max(signintime) FROM  actioninfo WHERE actionType='1' AND actionSubType ='1' AND userId ='"+useId+"' AND signintime>('"+date+"'  - INTERVAL 1 SECOND) AND  signintime< INTERVAL 1 DAY + '"+date+"'";
					 	    		                	  List <Map>  selectList =systemService.queryForList(sql, parameters);
					 	    		                	  if(selectList.size()>0&&selectList!=null&&selectList.get(0).get("Max(signintime)")!=null){
					 	    		                		  systemService.save(detail);  
					 	    		                		  String type ="1";
					 	    		                		 Insertrowout(null, map, sql,selectList,type);
					 	    		                	  }
					 		    		        	}else if ("1".equals(actionType)){
					 		    		        		  System.out.println("本次没有公司签出记录，可能在外勤");
					 	    		                	  sql="SELECT *,Max(signintime) FROM  actioninfo WHERE actionType='0' AND actionSubType ='1' AND userId ='"+useId+"' AND signintime>('"+date+"'  - INTERVAL 1 SECOND) AND  signintime< INTERVAL 1 DAY + '"+date+"'";
					 	    		                	  List <Map>  selectList =systemService.queryForList(sql, parameters);
					 	    		                	  if(selectList.size()>0&&selectList!=null&&selectList.get(0).get("Max(signintime)")!=null){
					 	    		                		  systemService.save(detail);   
					 	    		                		  String type = "0";
					 	    		                		 Insertrowout(null, map, sql,selectList, type);
					 	    		                	  }
					 		    		        	}
			 	    		                	
			 	    		                	// if(){}
			 	    		                  }
		 	    		                	
			 	    		                }
		 	    		           
				            			 
				            		 }
			    		        
		                	}
		 	    		                	
				            
				        }	    			
			            	
			     }
		   }
  	
		           
		}
	}
   
	public long getdate(String d1, String d2) {
		   long i = -1;
		   try {
		    SimpleDateFormat formatter = new SimpleDateFormat(
		      "yyyy-MM-dd HH:mm:ss");
		    ParsePosition pos = new ParsePosition(0);
		    ParsePosition pos1 = new ParsePosition(0);
		    Date dt1 = formatter.parse(d1, pos);
		    Date dt2 = formatter.parse(d2, pos1);
		    long l = dt1.getTime() - dt2.getTime();
		    i = l / (1000 * 60 * 60 );
		    // 这是他们相差的天数。
		    System.out.println("Hello World!=" + i);
		    
		   } catch (Exception e){
			}
		   return i;
		   }

	/**
	 * @return the file
	 */
	public File getFile() {
		return file;
	}

	/**
	 * @param file
	 *            the file to set
	 */
	public void setFile(File file) {
		this.file = file;
	}

	/**
	 * @return the fileFileName
	 */
	public String getFileFileName() {
		return fileFileName;
	}





	public void setSystemService(SystemService systemService) {
		this.systemService = systemService;
	}

	/**
	 * @param fileFileName
	 *            the fileFileName to set
	 */
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}


}